package com.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.domain.*;
import com.webservice.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/company")
public class CompanyController {

    @Resource
    private UserWebservice userWebservice;

    @Resource
    private BiddingWebservice biddingWebservice;

    @Resource
    private OrderWebservice orderWebservice;

    @Resource
    private ProcessWebservice processWebservice;

    @RequestMapping("/biding")
    public String companybiding(Model model, HttpServletRequest request){
        HttpSession session = request.getSession();
        User company = (User) session.getAttribute("user");
        model.addAttribute("company", company);
        List<Maintenance_order> orders =  orderWebservice.findByState(2,company.getId(),2);
        model.addAttribute("orders",orders);
        return "company/biding";
    }

    @RequestMapping("/historyorder")
    public String historyorder(String time, Model model, HttpServletRequest request){
        HttpSession session = request.getSession();
        User company = (User) session.getAttribute("user");
        model.addAttribute("company", company);
        System.out.println("你要查询的时间是********"+time);
        if (time != null) {
            List<Maintenance_order> maintenance_orders = new ArrayList<Maintenance_order>();
            maintenance_orders = orderWebservice.findHistoryByUser(company.getId(),time);
            model.addAttribute("orderlist", maintenance_orders);
        } else {
            List<Maintenance_order> maintenance_orders = new ArrayList<Maintenance_order>();
            Date date = new Date(System.currentTimeMillis());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            time = sdf.format(date);
            maintenance_orders = orderWebservice.findHistoryByUser(company.getId(),time);
            model.addAttribute("orderlist", maintenance_orders);
        }
        model.addAttribute("time",time);
        return "company/historyorder";

    }

    /**
     * 查看信息待竞单信息
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/pendingBid")
    public String approvePriceList(Model model, HttpServletRequest request)
    {
        HttpSession session = request.getSession();
        User company = (User) session.getAttribute("user");
        model.addAttribute("company", company);
        List<Maintenance_order> orders =  orderWebservice.findByState(2,company.getId(),1);
        model.addAttribute("orders",orders);
        return "company/pendingBid";
    }
    //维修反馈提交事件
    @RequestMapping("/submit")
    public int submit(@RequestBody Map<String,String> map,Model model, HttpServletRequest request)
    {
        HttpSession session = request.getSession();
        User company = (User) session.getAttribute("user");
        model.addAttribute("company", company);
        Date date1 = new Date();
        Date date2 = new Date();
        List<Expense_details> expense_detailsList = new ArrayList<Expense_details>();

        String expense;
        Expense_details expense_list = new Expense_details();
        Expense_details expense_list2 = new Expense_details();

        expense_list.setConsumable_name(map.get("name1"));
        expense_list2.setConsumable_name(map.get("name2"));

        expense_list.setConsumable_num(Float.parseFloat(map.get("num1")));
        expense_list2.setConsumable_num(Float.parseFloat(map.get("num2")));

        expense_list.setConsumable_price(Float.parseFloat(map.get("money1")));
        expense_list2.setConsumable_price(Float.parseFloat(map.get("money2")));

        expense_list.setOrder_id(Integer.parseInt(map.get("id")));
        expense_list2.setOrder_id(Integer.parseInt(map.get("id")));

        expense_list.setClassifier(map.get("classifer1"));
        expense_list2.setClassifier("classifer2");
        expense_list.setUnit_id(company.getId());
        expense_list2.setUnit_id(company.getId());

        expense_detailsList.add(expense_list);
        expense_detailsList.add(expense_list2);
        expense = JSON.toJSONString(expense_detailsList,true);
   //   List<Maintenance_order> orders =  orderWebservice.findByState(2,company.getId(),1);
    //  model.addAttribute("orders",orders);
        Maintenance_order order = orderWebservice.findOne(Integer.valueOf(map.get("id")));
        Bidding bid = new Bidding();
        bid.setCompany_id(company.getId());
        bid.setBidding_description(map.get("state"));
        bid.setEstimated_price(Float.valueOf(map.get("price")));//预估金额
        bid.setOrder_id(Integer.valueOf(map.get("id")));//维修单编号
        bid.setExpenseDetailsList(expense);//预测维修清单
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            date1 = sdf.parse(map.get("start_time"));
            date2 = sdf.parse(map.get("end_time"));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        bid.setStart_time(date1);
        bid.setFinished_time(date2);

        int i = biddingWebservice.addBidding(bid);
        return i;
    }

    //竞单申请页面
    @RequestMapping("/applypage")
    public String applypage(Integer id,Model model, HttpServletRequest request)
    {
        HttpSession session = request.getSession();
        User company = (User) session.getAttribute("user");
        model.addAttribute("company",company);
        String a = "";
        String b = "";
        Maintenance_order order = orderWebservice.findOne(id);
        List<Maintenance_request> requests = new ArrayList<>();
        requests = orderWebservice.findAllRequest(id);
        String photoes = order.getProblem_image();
        List<String> map = new ArrayList<>();
        System.out.println(photoes);
        String video = order.getProblem_video();
        String maps="";
        if(video!=null){
            String[] strings = video.split(",");
            if (strings!=null){
                for (String str:strings){
                    maps=str;
                }
            }
            System.out.println("****");
            System.out.println(maps);
            System.out.println("****");
            model.addAttribute("video",maps);
        }
        if(photoes!=null){
            String[] strings = photoes.split(",");
            if (strings!=null){
                for (String str:strings){
                    if (str!=null && !str.equals("")){
                        map.add(str);
                    }
                }
            }
            model.addAttribute("photoes",map);
        }
        if(requests!=null) {
            for (Maintenance_request request1 : requests) {
                if (request1.getRole_id() ==2) {
                    a = request1.getMaintenance_request();//这是设备管理员的要求
                    System.out.println(a);
                }
                if (request1.getRole_id() == 3) {
                    b = request1.getMaintenance_request();
                    System.out.println(b);
                }
            }
        }
        model.addAttribute("a",a);
        model.addAttribute("b",b);
        model.addAttribute("order",order);
        return "company/applypage";
    }
    //维修反馈页面
    @RequestMapping("/feedback")
    public String feedback(Integer id, Model model, HttpServletRequest request)
    {
        HttpSession session = request.getSession();
        User company = (User) session.getAttribute("user");
        model.addAttribute("company", company);
        List<Maintenance_request> requests = new ArrayList<>();
        System.out.println("&&&&"+id);
        requests = orderWebservice.findAllRequest(id);
        Maintenance_order order = orderWebservice.findOne(id);
        List<String> map = new ArrayList<>();
        String photoes = order.getProblem_image();
        if(photoes!=null){
             String[] strings = photoes.split(",");
                if (strings!=null){
                    for (String str:strings){
                        if (str!=null && !str.equals("")){
                            map.add(str);
                        }
                    }
                }
            }
        model.addAttribute("photoes",map);

        String videos = order.getProblem_video();
        List<String> map_video = new ArrayList<>();
        String a="";
        String b="";
        String c="";
        String d="";
        String e="";
        String f = "";

        if(videos!=null){
            String[] strs = videos.split(",");
            if(strs!=null){
                for (String str:strs){
                    if (str!=null && !str.equals("")){
                        map_video.add(str);
                    }
                }

            }
            model.addAttribute("video",map_video);
        }


        if(requests!=null) {
            for (Maintenance_request request1 : requests) {
                if (request1.getRole_id() == 2) {
                    a = request1.getMaintenance_request();//这是设备管理员的要求
                }
                if (request1.getRole_id() == 3) {
                    if(request1.getUser_name().equals(order.getEquipment_admin_name())){
                        f=request1.getMaintenance_request();
                    }else{
                        b = request1.getMaintenance_request();
                    }
                }
                if (request1.getRole_id() == 4) {
                    c = request1.getMaintenance_request();
                }
            }
        }
        model.addAttribute("a",a);
        model.addAttribute("b",b);
        model.addAttribute("c",c);
        model.addAttribute("f",f);
        model.addAttribute("orders",order);
        return "company/feedback";
    }
    //维修反馈上传
    @RequestMapping("/uppicture")
    @ResponseBody
    public int uppicture(MultipartFile[] photos,MultipartFile[] videos,MultipartFile[] listfile, String states, String final_price, Integer time, Integer id, Model model, HttpServletRequest request)
            throws IllegalStateException, IOException{
        HttpSession session = request.getSession();
        User company = (User) session.getAttribute("user");
        model.addAttribute("company", company);
            String str = "";
            String str2 = "";
            String str3 = "";
            String path = "D:/mmms-assets/";
            for (MultipartFile pic : photos) {
                if (!pic.isEmpty()) {
                    String originalFileName = pic.getOriginalFilename();
                    // 新的图片名称
                    String newFileName = UUID.randomUUID() + originalFileName.substring(originalFileName.lastIndexOf("."));
                    // 新的图片
                    File newFile = new File(path + newFileName);
                    // 将内存中的数据写入磁盘
                    pic.transferTo(newFile);
                    //创建文件名用于上传
                    str = str + newFileName + ",";
                }
            }
            System.out.println("已经完成图片下载！");
            for (MultipartFile vio : videos) {
                if (!vio.isEmpty()) {

                    String originalFileName = vio.getOriginalFilename();
                    // 新的图片名称
                    String newFileName2 = UUID.randomUUID() + originalFileName.substring(originalFileName.lastIndexOf("."));
                    // 新的图片
                    File newFile = new File(path + newFileName2);
                    // 将内存中的数据写入磁盘
                    vio.transferTo(newFile);

                    str2 = newFileName2;
                }
            }
            System.out.println("视频下载完成！");
            for (MultipartFile list : listfile) {
                if (!list.isEmpty()) {
                    String originalFileName = list.getOriginalFilename();
                    // 新的图片名称
                    String newFileName3 = UUID.randomUUID() + originalFileName.substring(originalFileName.lastIndexOf("."));
                    // 新的图片
                    File newFile = new File(path + newFileName3);
                    // 将内存中的数据写入磁盘
                    list.transferTo(newFile);
                    str3 = newFileName3;
                }
            }

            System.out.println("清单文件上传完成！");
            int y = processWebservice.maintenance_Finished(id, Float.valueOf(final_price), time, states, str, str2, "");
            System.out.println("y" + y);
            int x = processWebservice.uploadExpenseFile(id, str3);
            System.out.println("x" + x);
            return x + y;
    }
    //指派维修单确认
    @RequestMapping("/doingOrder")
    public String doingOrder( Model model, HttpServletRequest request)
    {
        HttpSession session = request.getSession();
        User company = (User) session.getAttribute("user");
        model.addAttribute("company", company);
        List<Maintenance_order> list_orders = orderWebservice.findOrderByUnit(company.getId());
        List<Maintenance_order> list = new ArrayList<Maintenance_order>();
        if(list_orders!=null) {
            for (Maintenance_order maintenance_order : list_orders) {
                if(maintenance_order.getOrder_state()==14){
                    list.add(maintenance_order);
                }
            }
        }

        model.addAttribute("orders",list);
        return "company/doingOrder";
    }
    //维修反馈撤回列表__在办维修列表
    @RequestMapping("/orderBack")
    public String orderBack( Model model, HttpServletRequest request)
{
    HttpSession session = request.getSession();
    User company = (User) session.getAttribute("user");
    model.addAttribute("company", company);
    List<Maintenance_order> list_orders = orderWebservice.findOrderByUnit(company.getId());
    List<Maintenance_order> list = new ArrayList<Maintenance_order>();
    if(list_orders!=null) {
        list.addAll(list_orders);
    }
    model.addAttribute("orders",list);
    return "company/orderBack";
}
    //维修反馈撤回
    @RequestMapping("/back")
    public String back(Integer id, Model model, HttpServletRequest request)
    {
        HttpSession session = request.getSession();
        User company = (User) session.getAttribute("user");
        model.addAttribute("company", company);
        System.out.println(id);
        int i = processWebservice.maintenance_turnBack(id);
        System.out.println(i);
        return "redirect:/company/orderBack";
    }
    //指派维修单待确认页面
    @RequestMapping("/ordermation")
    public String ordermation(Integer id, Model model, HttpServletRequest request,HttpServletResponse response)throws IOException
    {
        HttpSession session = request.getSession();
        User approver = (User) session.getAttribute("user");
        model.addAttribute("approver", approver);
        Maintenance_order maintenance_order = orderWebservice.findOne(id);
        String a = "";
        String b = "";
        String c = "";
        String f="";
        List<Maintenance_request> requests = new ArrayList<>();
        requests = orderWebservice.findAllRequest(id);
        String photoes = maintenance_order.getProblem_image();
        String videos = maintenance_order.getProblem_video();
        List<String> map = new ArrayList<>();
        List<String> map2 = new ArrayList<>();
        System.out.println(photoes);
        if(photoes!=null){
            String[] strings = photoes.split(",");
            if (strings!=null){
                for (String str:strings){
                    if (str!=null && !str.equals("")){
                        map.add(str);
                    }
                }
            }
            model.addAttribute("photoes",map);
        }
        if(videos!=null){
            String[] strs = photoes.split(",");
            if (strs!=null){
                for (String str:strs){
                    if (str!=null && !str.equals("")){
                        map2.add(str);
                    }
                }
            }
            model.addAttribute("videos",map2);
        }
        if(requests!=null) {
            for (Maintenance_request request1 : requests) {
                if (request1.getRole_id() == 2) {
                    a = request1.getMaintenance_request();//这是设备管理员的要求
                }
                if (request1.getRole_id() == 3) {
                    if(request1.getUser_name().equals(maintenance_order.getEquipment_admin_name())){
                        f=request1.getMaintenance_request();
                    }else{
                        b = request1.getMaintenance_request();
                    }
                }
                if (request1.getRole_id() == 4) {
                    c = request1.getMaintenance_request();
                }
            }
        }
        model.addAttribute("a",a);
        model.addAttribute("b",b);
        model.addAttribute("c",c);
        model.addAttribute("f",f);
        model.addAttribute("order",maintenance_order);
        return "/company/ordermation";
    }

    //维修方接受
    @RequestMapping("/agree")
    @ResponseBody
    public int agree(Integer id, Model model, HttpServletRequest request)
    {
        HttpSession session = request.getSession();
        User company = (User) session.getAttribute("user");
        model.addAttribute("company", company);
        int i = processWebservice.maintenanceAcceptDecision(id);
        System.out.println("这是维修方同意");
        return i;
    }

    //维修方拒绝
    @RequestMapping("/disagree")
    @ResponseBody
    public int disagree(Integer id,String states, Model model, HttpServletRequest request)
    {
        HttpSession session = request.getSession();
        User company = (User) session.getAttribute("user");
        model.addAttribute("company", company);
      //  int i = processWebservice.maintenanceRefuseDecision(id,states);
        System.out.println("这是维修方拒绝");
        return 0;
    }
    @RequestMapping("/norepaired")
    @ResponseBody
    public int norepaired(Integer id,String states, Model model, HttpServletRequest request)
    {
        HttpSession session = request.getSession();
        User company = (User) session.getAttribute("user");
        model.addAttribute("company", company);
        System.out.println("*****00");
       int i = processWebservice.maintenance_Fault(id,states);
        System.out.println("*****00");
        return i;
    }
}